//
//  BaseViewController.m
//  BaseFrame
//
//  Created by apple on 16/9/28.
//  Copyright © 2016年 com.mxh. All rights reserved.
//

#import "BaseViewController.h"
#import <MBProgressHUD/MBProgressHUD.h>

@interface BaseViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic,copy) void(^selectPhotoHandle)(UIImage *img);

@end

@implementation BaseViewController
//设置状态栏颜色
//- (void)setStatusBarBackgroundColor:(UIColor *)color {
//
//    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
//    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
//        statusBar.backgroundColor = color;
//    }
//}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
//    [self changeNavigationBarBackgroundColor:theme_navigation_color];
    [self changeNavigationBarBackgroundColor:getColor(mainColor)];
}
- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置状态栏背景
//    UIView *statusBarView = [[UIView alloc]   initWithFrame:CGRectMake(0, -STATUS_HEIGHT,    self.view.bounds.size.width, STATUS_HEIGHT)];
//    statusBarView.backgroundColor = getColor(mainColor);
//    [self.navigationController.navigationBar addSubview:statusBarView];
    
    //布局 不延伸
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    //导航栏下的横线
//    [self.navigationController.navigationBar setShadowImage:[UIImage imageWithColor:getColor(whiteColor)]];
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
//    [self.navigationController.navigationBar setTranslucent:NO];
    
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    // 状态栏和导航栏字体全变为白色
//    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    // 导航栏字体颜色
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:getColor(blackColor)};
    // 设置导航栏背景颜色
//    self.navigationController.navigationBar.backgroundColor = getColor(mainColor);
//    self.navigationController.navigationBar.barTintColor = getColor(mainColor);
    
    
    
//    CAGradientLayer *gradientLayer = [CAGradientLayer layer];  // 设置渐变效果
//    gradientLayer.bounds = CGRectMake(0, 0, SCREEN_WIDTH, 64);
//    gradientLayer.position = CGPointMake(SCREEN_WIDTH/ 2, 32);
//    gradientLayer.colors = [NSArray arrayWithObjects:(id)[getColor(@"468df2") CGColor],(id)[getColor(@"5abcf9") CGColor], nil];
//    gradientLayer.startPoint = CGPointMake(0, 0.5);
//    gradientLayer.endPoint = CGPointMake(1.0, 0.5);
//    [[[self.navigationController.navigationBar.subviews firstObject] layer] addSublayer:gradientLayer];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"";
    self.navigationItem.backBarButtonItem = backItem;
    
    //设置tab title颜色
    [UITabBar appearance].tintColor = getColor(mainColor);
    //设置背景颜色
    [UITabBar appearance].barTintColor = [UIColor whiteColor];
}

- (MBProgressHUD *)progressHUD {
    if (!_progressHUD) {
        _progressHUD = [[MBProgressHUD alloc]initWithView:self.view];
        //        _progressHUD.frame = [UIScreen mainScreen].bounds;
        //        _progressHUD.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.75];
    }
    return _progressHUD;
}

#pragma mark - Custom Method
/**
 *  显示错误的code码和信息
 *
 *  @param status    返回的code码
 *  @param message 返回的信息
 */
- (void) failureWithStatus:(NSString*)status message:(NSString*)message{
    NSLog(@"status:%@,msg:%@", status,message);
}

/**
 *  显示错误信息
 *
 *  @param error 返回的错误信息
 */
- (void) showError:(NSError*)error{
    switch (error.code) {
        case NSURLErrorNotConnectedToInternet:
            ShowMessage(@"请检查你的网络");
            break;
        case NSURLErrorTimedOut:
            ShowMessage(@"请求超时，请查看你的网络");
            break;
        case NSURLErrorCannotConnectToHost:
            ShowMessage(@"服务器繁忙，请稍后重试");
            break;
        case NSURLErrorNetworkConnectionLost:
            ShowMessage(@"处理过程中网络中断，请重试");
            break;
        default:
            ShowMessage(@"未知错误");
            break;
    }
}

/**
 *  显示大菊花
 */
-(void)showprogressHUD{
    self.tabBarController.view.userInteractionEnabled = NO;
    self.navigationController.view.userInteractionEnabled = NO;
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self.navigationController.view addSubview:self.progressHUD];
    [self.progressHUD showAnimated:YES];
}

/**
 *  隐藏大菊花
 */
-(void)hiddenProgressHUD{
    self.tabBarController.view.userInteractionEnabled = YES;
    self.navigationController.view.userInteractionEnabled = YES;
    [self.progressHUD hideAnimated:YES];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self.progressHUD removeFromSuperview];
}

/**
 弹出提示框 选择相机或者相册
 
 @param selectPhotoHandle 选中或拍摄的图片
 */
- (void)selectPhotoAlbumWithSelectPhotoHandle:(void (^)(UIImage *))selectPhotoHandle{
    self.selectPhotoHandle = selectPhotoHandle;
    
    UIAlertController *av = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self takePhoto];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self LocalPhoto];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [av addAction:action1];
    [av addAction:action2];
    [av addAction:cancelAction];
    [self presentViewController:av animated:YES completion:nil];
}

//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else{
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage* image = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    if (self.selectPhotoHandle) {
        self.selectPhotoHandle(image);
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

/**
 *  拨打电话
 *
 *  @param phoneNumber 号码
 */
- (void)callPhone:(NSString *)phoneNumber{
    UIAlertController *av = [UIAlertController alertControllerWithTitle:@"拨打电话" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [av addAction:action1];
    [av addAction:action2];
    [self presentViewController:av animated:YES completion:nil];
}
//- (void) showAlert
//{
//    //显示提示框
//    //过时
//    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"message" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil];
//    //    [alert show];
//    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Title"
//                                                                   message:@"您还没有登录,是否登录..."
//                                                            preferredStyle:UIAlertControllerStyleAlert];
//
//    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault
//                                                          handler:^(UIAlertAction * action) {
//                                                              //响应事件
//                                                              NSLog(@"action = %@", action);
//
//                                                          }];
//    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault
//                                                         handler:^(UIAlertAction * action) {
//                                                             //响应事件
//                                                             NSLog(@"action = %@", action);
//                                                         }];
//
//    [alert addAction:defaultAction];
//    [alert addAction:cancelAction];
//    [self presentViewController:alert animated:YES completion:nil];
//}
- (NSString *)md5:(NSString *)string{
    const char *cStr = [string UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02X", digest[i]];
    }
    
    return result;
}
// 改变状态栏颜色 和导航栏颜色
-(void)changeNavigationBarBackgroundColor:(UIColor *)barBackgroundColor{
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]){
        NSArray *subviews =self.navigationController.navigationBar.subviews;
        for (id viewObj in subviews) {
            if (ISIOS10) {
                //iOS10,改变了状态栏的类为_UIBarBackground
                NSString *classStr = [NSString stringWithUTF8String:object_getClassName(viewObj)];
                if ([classStr isEqualToString:@"_UIBarBackground"]) {
                    UIImageView *imageView=(UIImageView *)viewObj;
                    imageView.hidden=YES;
                }
            }else{
                //iOS9以及iOS9之前使用的是_UINavigationBarBackground
                NSString *classStr = [NSString stringWithUTF8String:object_getClassName(viewObj)];
                if ([classStr isEqualToString:@"_UINavigationBarBackground"]) {
                    UIImageView *imageView=(UIImageView *)viewObj;
                    imageView.hidden=YES;
                }
            }
        }
        UIImageView *imageView = [self.navigationController.navigationBar viewWithTag:111];
        if (!imageView) {
            imageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, -20, SCREEN_WIDTH, 64)];
            imageView.tag = 111;
            [imageView setBackgroundColor:barBackgroundColor];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController.navigationBar insertSubview:imageView atIndex:0];
            });
        }else{
            [imageView setBackgroundColor:barBackgroundColor];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.navigationController.navigationBar sendSubviewToBack:imageView];
            });
            
        }
        
    }
}
@end
